<?php
namespace App\Controllers\Goods;
use \App\Libs\Base\Constant;
use App\Models\Goods\Goods;
use App\Models\Goods\GoodsImg;
use App\Models\Goods\GoodsAffiliate;
use App\Models\Store\Store;
use App\Models\Collect\Collect;

/**
*	获取商品详情
*/
class GoodsDetail extends \App\Libs\Base\BaseAction
{
	 protected function beforeRun() {
         parent::beforeRun();
         //$this->needLogin = TRUE;
     }
	public function execute() {
		$gid = (int)$this->request->get('gid');
		$lat = $this->request->get('lat');
		$lnt = $this->request->get('lnt');
		if( isset( $this->session->user->id ) ){
			$uid = $this->session->user->id;
		}
		if( empty( $gid ) ){
			return \App\Libs\Views\Json::view(1, '未查到相关商品', null);
		}
		
		//查询是否存在KEY
		$goods = Goods::find(array(
			'id = :gid:',
			'columns'=>'id,sid,goods_name,goods_price,sale_price,goods_desc',
			'bind' => array('gid'=>$gid,),
		));
		if( !empty( $goods ) ){
			//是否收藏 
			$collectHave = 0;
			if( empty( $uid ) ){
				$collectHave = '0';
			}else{
				$collect = Collect::find(array(
					' uid = :uid: and cid = :cid: and type = 1',
					'bind' => array( 'uid'=>$uid , 'cid'=>$gid )
				));
				if( !empty( $collect ) ){
					$collectHave = 1;
				}
			}
			
			//查询其他信息
			//店铺信息
			$store = Store::find(array(
				'id = :sid:',
				'bind' => array('sid'=>$goods->sid),
			))->toArray();
			$store['distance'] = \App\Libs\Helper\CommonHelper::getDistance( $lat , $lnt , $store['latitude'] , $store['longitude'] );
				
			$affiliate = GoodsAffiliate::find(array(
				'gid = :gid:',
				'bind' => array('gid'=>$goods->id),
			));
			$img = GoodsImg::find(array(
				'gid=:gid: and show_status = 2',
				'bind' => array('gid'=>$goods->id),
			));
			if(!empty($img)){
			 $imgurl = json_decode($img->imgurl);
			}else{
			$imgurl = [];
			}

			if( !empty( $affiliate ) ){
				$affiliate = $affiliate->toArray();
				$affiliate['xuzhi'] = json_decode( $affiliate['xuzhi'] , true );
			}
			//格式刷价格：
            $goods->goods_price = Goods::formatPrice($goods->goods_price);
			$goods->sale_price = Goods::formatPrice($goods->sale_price);
			return \App\Libs\Views\Json::view(0, '成功', ['info'=>$goods,'store'=>$store,'affiliate'=>$affiliate,'img'=>$imgurl,'collectHave'=>$collectHave]);
		}else{
			return \App\Libs\Views\Json::view(1, '未查到相关商品', null);
		}
		
	}
}
